package com.mvvm.store.ui.into;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Toast;

import androidx.viewpager.widget.ViewPager;

import com.leo.utilspro.utils.ToastUtils;
import com.mvvm.store.R;
import com.mvvm.store.base.BaseFragment;
import com.mvvm.store.base.NormalViewModel;
import com.mvvm.store.bean.BannerBean;
import com.mvvm.store.bean.StockUpParasBean;
import com.mvvm.store.bean.basebean.IntoMaterialBean;
import com.mvvm.store.bean.basebean.MaterialInfoBean;
import com.mvvm.store.bean.basebean.MeterialInfroResultBean;
import com.mvvm.store.bean.basebean.StockUpResultBean;
import com.mvvm.store.customview.CustomProgress;
import com.mvvm.store.databinding.FragmentDemoBinding;
import com.mvvm.store.databinding.FragmentMaterialInfoBinding;
import com.mvvm.store.roombatabase.IntoMaterDatabase;
import com.mvvm.store.roombatabase.IntoMaterialDao;
import com.mvvm.store.ui.into.adaper.MaterialInfoAdapter;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;


/**
 * Created by leo     MVVM
 * @author  zhouchangyi
 * on 2021/06/15.   物料信息界面
 */
public class MaterialInfoFragment extends BaseFragment<IntoViewModel, FragmentMaterialInfoBinding>{

    int index;
    private MaterialInfoAdapter infoAdapter;
    private int curPage = 0;
    private ArrayList<IntoMaterialBean> materialInfoBeans = new ArrayList<>();
    private CustomProgress dialog;
    private String[] items = {"广州本田", "一汽大众", "奔驰", "宝马"};
    private String codeResult="";
    private  IntoMaterialDao intoMaterialDa;
    private  List<IntoMaterialBean> materialInfoBeanss;

    private int TIME = 1000;  //每隔1s执行一次.
    Handler handler = new Handler();




    public static MaterialInfoFragment newInstance(final String name, ViewPager viewPager) {
        MaterialInfoFragment mFragment = new MaterialInfoFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", name);
        mFragment.setArguments(bundle);
        return mFragment;
    }

    Runnable runnables=new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, TIME);
                //刷新数据
               // materialInfoBeans.clear();
               // getMaterInforTointent();
            System.out.println("出库扫码监听数据,刷新列表");
                materialInfoBeanss = intoMaterialDa.getMaterialInfo(codeResult);
                materialInfoBeans.clear();
                for (int i = 0; i < materialInfoBeanss.size(); i++) {
                    materialInfoBeans.add(materialInfoBeanss.get(i));
                }
                infoAdapter.notifyDataSetChanged();

        }
    };



    @Override
    protected int getContentViewId() {
        return R.layout.fragment_material_info;
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        handler.postDelayed(runnables, TIME); // 在初始化方法里.
        intoMaterialDa= IntoMaterDatabase.getInstance(getActivity()).materialDao();
        //获取到扫码出来的单号
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("codeInfo", MODE_PRIVATE);
        codeResult=sharedPreferences.getString("codeResult","");
        System.out.println("入库----codeResult--------------------"+codeResult);
        binding.tvOrderNumber.setText(codeResult+"");
        if(dialog==null) {
            dialog = CustomProgress.show(getActivity(), "", true, null);
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(500);//休眠3秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                /**
                 * 要执行的操作
                 */
                dialog.dismiss();
            }
        }.start();

        binding.includeEmpty.setTextEmpty("瞅啥，没有你的物料~");
        binding.includeEmpty.setImageEmpty(R.mipmap.no_data);
        infoAdapter = new MaterialInfoAdapter();
        infoAdapter.setDataList(materialInfoBeans);
        binding.recyclerView.setAdapter(infoAdapter);

        getMaterInforTointent();

    }

    private void getMaterInforTointent(){
        //调用接口获取数据
        mViewModel.getMaterialInfo(codeResult).observe(this,resource->resource.handler(new OnCallback<List<MeterialInfroResultBean>>() {
            @Override
            public void onSuccess(List<MeterialInfroResultBean> data) {
                System.out.println("接口返回的数据"+data.toString()+"");
                if(data.size()==0 && materialInfoBeans.size()==0){
                    binding.includeEmpty.relativeNull.setVisibility(View.VISIBLE);
                }else {
                    binding.includeEmpty.relativeNull.setVisibility(View.GONE);
                    if (data.size() > 0) {
                        for (int i = 0; i < data.size(); i++) {
                            binding.tvIntoSupplierName.setText(data.get(i).getSupplierName() + "");
                            binding.tvOrderNumber.setText(data.get(i).getDeliveryOrderNo() + "");
                            //将数据存放到本地数据库中
                            if (data.size() > 0) {
                                //根据订单号和零件号查询本地数据库是否有对应的数据
                                List<IntoMaterialBean> intoMaterialBeanListTolaod = intoMaterialDa.getMaterialInfoByOrder(data.get(i).getDeliveryOrderNo(), data.get(i).getPartCode());
                                if (intoMaterialBeanListTolaod.size() > 0) {
                                    //本地有不需要管理
                                    System.out.println("查询的该订单号对应的零件号本地数据存在了"+intoMaterialBeanListTolaod.toString());
                                } else {

                                    //添加到本地数据库
                                    IntoMaterialBean intoMaterialBean = new IntoMaterialBean();
                                    intoMaterialBean.setOrderNumber(data.get(i).getDeliveryOrderNo());
                                    intoMaterialBean.setOddNumber(data.get(i).getPartCode());
                                    intoMaterialBean.setOddName(data.get(i).getPartName());
                                    intoMaterialBean.setPackNumber(Integer.parseInt(data.get(i).getBoxNum()));
                                    intoMaterialBean.setSumNumber(Integer.parseInt(data.get(i).getAogNum()));
                                    intoMaterialBean.setSupplierName(data.get(i).getSupplierName());
                                    intoMaterialBean.setSnpNumber(Integer.parseInt(data.get(i).getSnp()));
                                    intoMaterialBean.setRealToPack(0);
                                    intoMaterialBean.setRealToNumber(0);
                                    intoMaterialDa.insertAll(intoMaterialBean);

                                }

                            } else {
                                ToastUtils.showToast("该订单还没有对应的零件标签！请联系仓库管理员！");
                            }
                        }
                        //添加完进行查询刷新适配器
                        materialInfoBeanss = intoMaterialDa.getMaterialInfo(codeResult);
                        for (int i = 0; i < materialInfoBeanss.size(); i++) {
                            materialInfoBeans.add(materialInfoBeanss.get(i));
                        }
                        infoAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showToast("暂无入库信息");
                    }
                }
            }
        }));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(handler!=null) {
            handler.removeCallbacks(runnables);
        }
    }

    @Override
    protected void setListener() {
    binding.setOnClickListener(this::onClick);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_material:
              //  showDialog();
                break;
            default:
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            System.out.println("MaterialInfoFragment----hidden");
        }else {
            System.out.println("MaterialInfoFragment------no----hidden");
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //TODO 刷新数据方法在这里调用
            System.out.println("MaterialInfoFragmentsetUserVisibleHint刷新数据");
         if(infoAdapter!=null && !TextUtils.isEmpty(codeResult)) {
             materialInfoBeanss = intoMaterialDa.getMaterialInfo(codeResult);
             materialInfoBeans.clear();
             for (int i = 0; i < materialInfoBeanss.size(); i++) {
                 materialInfoBeans.add(materialInfoBeanss.get(i));
             }
             infoAdapter.notifyDataSetChanged();
         }

        }
    }

    private void showDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), items + "", Toast.LENGTH_SHORT);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getActivity(), "取消", Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog mDialog = builder.create();
        mDialog.show();
        Window window = mDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.popupAnimation);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setCancelable(true);
    }

}
